from ldap3 import Server, Connection, ALL, MODIFY_REPLACE

s = Server("localhost", get_info=ALL)
c = Connection(s, user="cn=admin,dc=hr,dc=cn",password="admin")

c.bind()

# print(c.extend.standard.who_am_i())
# # # 添加组织
# res = c.add("OU=hr_hr1,dc=hr,dc=cn",object_class='OrganizationalUnit')

# print(res)
# print(c.result)

# 添加组群
# ldap_attr = {}
# ldap_attr["objectClass"] = ['top', 'posixGroup']
# ldap_attr["gidNumber"] = '1'

# c.add('cn=mygroup1,dc=hr,dc=cn',attributes=ldap_attr)
# print(c.result)


# 添加人员
# ldap_attr = {}
# ldap_attr['cn'] = "testhr6"
# ldap_attr['sn'] = "浮洪瑞"
# # ldap_attr['uid'] = "1"
# ldap_attr['userPassword'] = "123"

# user_dn = "cn=testhr6,cn=mygroup,dc=hr,dc=cn"

# c.add(dn=user_dn,object_class='inetOrgPerson',attributes=ldap_attr)
# print(c.result)


# 查询用户

user = c.search("dc=hr,dc=cn",'(&(cn=testhr5))',attributes=["*"])
print(user)
print(c.entries)


#修改用户
# c.modify('cn=testhr5,cn=mygroup,dc=hr,dc=cn',{'uid':[(MODIFY_REPLACE, ['2'])]})
# print(c.result)

# user = c.search("dc=hr,dc=cn",'(&(cn=testhr5))',attributes=["*"])
# print(user)
# print(c.entries)


#删除用户
c.delete(dn='cn=testhr5,cn=mygroup,dc=hr,dc=cn')
print(c.result)


user = c.search("dc=hr,dc=cn",'(&(cn=testhr5))',attributes=["*"])
print(user)
print(c.entries)